package cn.smbms.interceptor;

import cn.smbms.pojo.User;
import cn.smbms.tools.Constants;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录校验过滤器
 */
@WebFilter
@Component("sessionFilter")
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //获取请求路径
        String uri = request.getRequestURI();
        if(uri.contains("/dologin.html")||uri.contains("/login.html")){
            //如果当前请求路径包含登录，直接放过
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //第一步获取session
            HttpSession session=request.getSession();
            //从session中获取当前登录对象
            User user= (User) session.getAttribute(Constants.USER_SESSION);
            if(user==null){
                response.sendRedirect(request.getContextPath()+"/401.jsp");
            }else {
                //校验通过，继续往下走
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
